import { actions } from 'mirrorx'
import { holderKeys, insureCustKeys, beneficiaryCustKeys } from 'lib/attrData'
import { API } from '../pages/api'

export default {
  name: 'insureModel',
  initialState: {
    blocksMap: {},
    initValueObj: {},
    initInfo: {},
    errorMap: {}
  },
  reducers: {
    setInitInfo (state, data) {
      return Object.assign({}, state, { initValueObj: data.initValueObj, initInfo: data.initInfo })
    },
    setBlockInfo (state, data) {
      return Object.assign({}, state, { blocksMap: data })
    },

    setErrorMap (state, data) {
      return Object.assign({}, state, { errorMap: data })
    },
    clearErrorMap (state) {
      return Object.assign({}, state, { errorMap: {} })
    }

  },
  effects: {
    requestInsureInfo (callback) {
      let cuid = T.urlQuery('cuid') || 'Adsfyh4540887f'
      let sessionKey = 'insure_' + cuid
      let storageInfo = T.sessionStorage.get(sessionKey)
      storageInfo = storageInfo ? JSON.parse(storageInfo) : {}

      let initValueObj = {
        1: storageInfo.holder ? [storageInfo.holder] : null,
        2: storageInfo.insurant ? [storageInfo.insurant] : null
      }
      let initInfo = storageInfo

      actions.insureModel.setInitInfo({ initValueObj, initInfo })
      if (callback) {
        let param = { initValueObj, initInfo }
        callback(param)
      }
    },
    requestBlockInfo (callback) {
      T.fetch2({
        url: API.dynamicFactors.path,
        loading: true,
        data: {
          'goodsId': T.urlQuery('goodsId'),
          'channelGoodsId': T.urlQuery('channelGoodsId'),
          userId: ''
        }
      }).then((result) => {
        if (result.success) {
          let data = result.value || {}

          actions.insureModel.setBlockInfo({
            1: data.policyHolderFactors || [],
            2: data.insuredFactors || [],
            3: []
          })

          callback && callback()
        }
      })
    }
  }
}
